package com.example.administrator.appstpremvpdemo.helper;

import android.app.Activity;
import android.os.Build;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import rx.functions.Action1;

/**
 * @Author Administrator
 * @Date 2017/12/11
 * @description 定义一个专门辅助处理动态敏感权限问题的帮助类
 * @function
 */

public class PermissionHelper {

    private Activity mActivity;
    private RxPermissions mRxPermissions;

    public PermissionHelper(Activity activity) {
        mActivity = activity;
        mRxPermissions = new RxPermissions(activity);//内部单例实现
    }

    public void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestReadWritePermission();
        }
    }

    private void requestReadWritePermission() {
        mRxPermissions.request("android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.READ_PHONE_STATE",
                "android.permission.INTERNET").subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean grante) {
                if (grante) {
                    mCheckAllPermissions.permissionsGranted();
                } else {
                    Toast.makeText(mActivity, "请打开权限", Toast.LENGTH_SHORT).show();
                    //TODO 如果用户勾选了默认不在弹出权限框的话，就弹我们应用自己的框
                }
            }
        });
    }

    public void setCheckAllPermissions(ICheckAllPermissions checkAllPermissions) {
        mCheckAllPermissions = checkAllPermissions;
    }

    private ICheckAllPermissions mCheckAllPermissions;

    /**
     * 当权限申请成功的回调
     */
    public interface ICheckAllPermissions {
        void permissionsGranted();
    }

}
